<?php

namespace app\bsadmin\controller;

use think\facade\View;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Db;
use think\cache\driver\Redis;
use helper\URL;
use helper\Dir;
use helper\ToXml;
use helper\Time;
use XYCms\Email as SendEmail;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\CompanyIndustry as CompanyIndustryModel;
use app\common\UploadFile;
use app\bsadmin\model\ApiRoute as ApiRouteModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\User as UserModel;
use app\common\model\School as SchoolModel;
use app\common\model\Specialities as SpecialitiesModel;
use app\common\model\Jobs as JobsModel;
use XYCms\Push;
use XYCms\PushRelease;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\model\Orders as OrdersModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\controller\Orders as OrdersController;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config as AliConfig;
use app\common\model\NotifyAlipay as NotifyAlipayModel;
use app\common\model\NotifyWxpay as NotifyWxpayModel;
use app\common\model\UserWx as UserWxModel;
use app\common\model\NotifyBaidu as NotifyBaiduModel;
use app\bsadmin\model\SubWebsite1 as SubWebsite1Model;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\Timing as TimingModel;
use helper\Wechat as WechatHelper;
use helper\Kuaishou as KuaishouHelper;
use think\Exception;
use XYCms\Sms;
use XYCms\Im as XYCMSIm;
use applepay\ApplePay;
use xin\helper\Func;
use XYCms\WorkWeChat;

class Test extends Base
{
    public function index()
    {
        $G = request()->get();
        if (!empty($G['action'])) {
            switch ($G['action']) {
                case 'createMessage':
                    $this->createMessage();
                    break;
                case 'sendPush':
                    $this->sendPush();
                    break;
                case 'PushRelease':
                    $this->PushRelease();
                    break;
                case 'rights_handle':
                    $this->rights_handle();
                    break;
                case 'TRUNCATE':
                    $this->TRUNCATE_handle();
                    break;
                case 'init_vip':
                    $this->init_vip();
                    break;
                case 'createVersionPackage':
                    return $this->createVersionPackage();
                    break;
                case 'openZip':
                    $this->openZip();
                    break;
                case 'copyAppApi':
                    $this->copyAppApi();
                    break;
                case 'showApi':
                    $this->showApi();
                    break;
                case 'work_wechat_token':
                    $this->workWechatToken();
                    break;
            }
        }
    }

    protected function workWechatToken()
    {
        Cache::delete('work_wechat|COMMON_ACCESS_TOKEN');
        Cache::delete('work_wechat|CONTACT_ACCESS_TOKEN');
        $api = new WorkWeChat();
        $api->getContactAccessToken();
        dump(['基础通用access_token' => Cache::get('work_wechat|COMMON_ACCESS_TOKEN')]);
        dump(['通讯录专用access_token' => Cache::get('work_wechat|CONTACT_ACCESS_TOKEN')]);
        // Cache::set('work_wechat|ACCESS_TOKEN', 'aMqudX6bTCmHU_nOS8h4OPtTP_Ks-ysClhoBNHRGZbr9QajX_pRB4QqP6XHNRCefqbkt2lwtm4D231TcIZb5RmudZwj00n8WVt-_03SO49uIcdjCsWaSmWyVbJdbY8VV2V0EBt6YsmWNLQt3-HLBsJvPdDv7QmDawn6RsEjXa9d1HAkjyqqRe13-Vx8HTGqm_FQTWtwsRp0Yf1GziXJF3g', 6000);
    }

    protected function createVersionPackage()
    {

        $version_name = request()->get('version_name');
        $root_path = root_path();
        $path = $root_path . 'package/' . $version_name;
        $filelist = @file_get_contents($path . '/package.log');
        if (!$filelist)
            return '备份清单不存在';
        $filelist = array_unique(explode("\n", $filelist));
        $filename = $path . '/packages.zip';
        if (file_exists($filename))
            unlink($filename);
        $zip = new \ZipArchive;
        if ($zip->open($filename, \ZIPARCHIVE::CREATE) !== TRUE) {
            return '无法打开备份，或者备份创建失败';
        }
        foreach ($filelist as $k => $v) {
            if (!$v) break;
            $filepath = str_replace("\r", '', $root_path . $v);
            if (is_dir($filepath)) {
                $this->addPathToZip($zip, $filepath, $root_path);
            } else {
                if (file_exists($filepath))
                    $zip->addFile($filepath, $v);
            }
        }
        $zip->close();
        return 'ok';
    }
    protected function addPathToZip($zip, $filepath, $root_path)
    {
        $files = Dir::tree($filepath);
        foreach ($files as $key => $value) {
            if (is_dir($value['path'])) {
                $this->addPathToZip($zip, $value['path'], $root_path);
            } else {
                if (file_exists($value['path']))
                    $zip->addFile($value['path'], str_replace($root_path, '', $value['path']));
            }
        }
    }

    protected function openZip()
    {
        if (is_file(root_path() . 'app/common.php')) {
            echo "string";
        }
        die;
        $version_name = request()->get('version_name');
        $root_path = root_path();
        $path = $root_path . 'package/' . $version_name;
        $filename = $path . '/packages.zip';
        $zip = new \ZipArchive;
        if ($zip->open($filename) === TRUE) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $contents = $zip->getNameIndex($i);
                p($contents);
            }
            $zip->close();
        }
        echo 'ok';
    }
    public function init_vip()
    {
        $UpdateUser = new \app\common\service\queue\UpdateUser;
        $UpdateUser->init_user_vip_handle();
    }
    public function TRUNCATE_handle()
    {
        die;
        $table = [
            'xy_admin_log',
            'xy_admin_login_log',
            'xy_ads',
            'xy_api_log',
            'xy_app_version',
            'xy_article',
            'xy_article_content',
            'xy_blacklist',
            'xy_company',
            'xy_company_attestation',
            'xy_company_blacklist',
            'xy_company_browse',
            'xy_company_collection',
            'xy_company_content',
            'xy_company_demeanor',
            'xy_company_development_history',
            'xy_company_executives',
            'xy_company_view',
            'xy_feedback',
            'xy_files',
            'xy_im_contacts',
            'xy_invite_aninterview',
            'xy_invite_aninterview_video',
            'xy_invoice',
            'xy_invoice_info',
            'xy_invoice_mail_address',
            'xy_job_fair',
            'xy_job_fair_booth',
            'xy_job_fair_booth_cate',
            'xy_job_fair_booth_status',
            'xy_job_fair_company',
            'xy_job_fair_contacts',
            'xy_job_fair_content',
            'xy_job_fair_resume',
            'xy_job_fair_vip',
            'xy_jobs',
            'xy_jobs_browse',
            'xy_jobs_collection',
            'xy_jobs_contacts',
            'xy_jobs_delivery_resume',
            'xy_jobs_examine_log',
            'xy_jobs_extension_log',
            'xy_jobs_refresh_auto',
            'xy_jobs_refresh_log',
            'xy_jobs_report',
            'xy_links',
            'xy_notify_alipay',
            'xy_notify_applepay',
            'xy_notify_wxpay',
            'xy_orders',
            'xy_push_message',
            'xy_push_message_content',
            'xy_push_queue',
            'xy_push_task',
            'xy_resume',
            'xy_resume_blacklist',
            'xy_resume_browse',
            'xy_resume_certificate',
            'xy_resume_collection',
            'xy_resume_consignment',
            'xy_resume_downloaded',
            'xy_resume_educational_experience',
            'xy_resume_employment_intention',
            'xy_resume_examine_log',
            'xy_resume_language_ability',
            'xy_resume_project_experience',
            'xy_resume_refresh',
            'xy_resume_refresh_log',
            'xy_resume_report',
            'xy_resume_self_description',
            'xy_resume_specialty_label',
            'xy_resume_training_experience',
            'xy_resume_work_experience',
            'xy_resume_works',
            'xy_score_task_complete',
            'xy_sms_send_log',
            'xy_statistics',
            'xy_user',
            'xy_user_apple',
            'xy_user_devices',
            'xy_user_info',
            'xy_user_invoice',
            'xy_user_login_log',
            'xy_user_mail_address',
            'xy_user_notice',
            'xy_user_qq',
            'xy_user_real_name',
            'xy_user_real_name_log',
            'xy_user_score',
            'xy_user_timer',
            'xy_user_vip',
            'xy_user_vip_rule',
            'xy_user_vip_rule_log',
            'xy_user_wx',
        ];
        foreach ($table as $k => $v) {
            Db::query('TRUNCATE TABLE ' . $v);
        }
        Db::query('ALTER TABLE `xy_user` AUTO_INCREMENT = 100000');
        echo "已删档";
    }
    public function insertExcel()
    {
        return;
        $inputFileName = './uploads/data3.xls';
        $sheetname = 'Sheet2';
        $inputFileType = IOFactory::identify($inputFileName);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setLoadSheetsOnly($sheetname);
        $spreadsheet = $reader->load($inputFileName);
        $workSheet = $spreadsheet->getActiveSheet();
        $Data = [];
        for ($i = 1; $i <= 744; $i++) {
            $Data[] = [
                'code'  => $workSheet->getCell('A' . $i)->getValue(),
                'specialities'  => $workSheet->getCell('B' . $i)->getValue(),
            ];
        }
        $SpecialitiesModel = new SpecialitiesModel;
        $SpecialitiesModel->saveAll($Data);
        return;
        $inputFileName = './uploads/data1.xls';
        $sheetname = 'sheet1';
        $inputFileType = IOFactory::identify($inputFileName);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setLoadSheetsOnly($sheetname);
        $spreadsheet = $reader->load($inputFileName);
        $workSheet = $spreadsheet->getActiveSheet();
        $Data = [];
        for ($i = 1; $i <= 265; $i++) {
            $Data[] = [
                'school_name'  => $workSheet->getCell('B' . $i)->getValue(),
                'school_code'  => $workSheet->getCell('C' . $i)->getValue(),
            ];
        }
        $SchoolModel = new SchoolModel;
        $SchoolModel->saveAll($Data);
    }
    public function rights_handle()
    {
        $orderList = OrdersModel::where(['status' => 1, 'pay_type' => 5])->field('otrade,pay_type,oprice')->limit(5)->select()->toArray();
        foreach ($orderList as $k => $v) {
            OrdersController::ordersHandle($v);
        }
    }
    public function readCell($column, $row, $worksheetName = '')
    {
        //  选定区域
        if ($row >= 1 && $row <= 7) {
            if (in_array($column, range('A', 'B'))) {
                return true;
            }
        }
        return false;
    }
    public function run()
    {
        $this->createVersionPackage();
    }
    public function sendPush()
    {
        $t1 = microtime(true);
        $PushTaskModel = PushTaskModel::where(['id' => 1517])->field('id,uid,client,event,status,data')
            ->withAttr('client', function ($v, $data) {
                return $v ? explode(',', $v) : '';
            })
            ->withAttr('data', function ($v, $data) {
                return json_decode($v, true);
            })->find();
        // $PushTaskModel->uid=100000;
        // $PushTaskModel->status=0;
        // $PushTaskModel->save();
        Push::send($PushTaskModel->toArray());
        $t2 = microtime(true);
        p($t1);
        p($t2);
        p($t2 - $t1);
    }
    public function PushRelease()
    {
        $t1 = microtime(true);
        try {
            $PushRelease = new PushRelease;
            $PushRelease->WechatPush();
            $PushRelease->SmsPush();
            $PushRelease->EmailPush();
            $PushRelease->AppPush();
        } catch (Exception $e) {
        }
        $t2 = microtime(true);
        p($t1);
        p($t2);
        p($t2 - $t1);
    }
    public function createMessage()
    {
        $msgData = json_encode(['title' => '测试标题', 'desc' => '测试描述', 'content' => '测试内容'], JSON_UNESCAPED_UNICODE);
        $PushTaskModel = new PushTaskModel;
        $PushTaskModel->uid = 100001;
        $PushTaskModel->client = null;
        $PushTaskModel->event = 'userNotice';
        $PushTaskModel->data = $msgData;
        $PushTaskModel->save();
    }
    public function hi()
    {
        $company_industry = CompanyIndustryModel::getCate();
        Cache::set('company_industry', $company_industry);
        p(Cache::get('company_industry'));
        die;
        return View::fetch();
    }
    public function copyAppApi()
    {
        $app_id = 8;
        $to_app_id = [4, 6, 8, 9, 10, 11];
        // ->whereNotIn('api_id',[113,116,117,144,195])
        // where(['app_id'=>$app_id])
        $api = ApiRouteModel::where('api_id', 'in', [984, 985])->field('app_id,api_method, api_name, api_controller, api_action, api_url, api_param, api_allow, api_ext, api_is_login, api_status')->select()->toArray();
        $Data = [];
        foreach ($api as $k => $v) {
            foreach ($to_app_id as $key => $app_id) {
                $temp = $v;
                $temp['app_id'] = $app_id;
                $temp['is_copy'] = $app_id;
                $Data[] = $temp;
            }
        }
        p($Data);
        // (new ApiRouteModel)->saveAll($Data);
        echo "OK";
    }
    public function showApi()
    {
        $app_id = 3;
        $to_app_id = 10;
        // ->whereNotIn('api_id',[113,116,117,144,195])
        // where(['app_id'=>$app_id])
        $api = ApiRouteModel::where('api_id', '>', 980)->whereIn('app_id', [1])->field('app_id,api_method, api_name, api_controller, api_action, api_url, api_param, api_allow, api_ext, api_is_login, api_status')->select()->toArray();
        echo json_encode($api, JSON_UNESCAPED_UNICODE);
        die;
    }

    // public function randomTag($tags = [], $targes = [])
    // {
    //     for ($i = 0; true; $i++) {
    //         $tag = $targes[random_int(0, count($targes) - 1)];
    //         if (count($tags) >= 4) {
    //             return $tags;
    //         } else {
    //             if (!in_array($tag, $tags)) {
    //                 $tags[] = $tag;
    //             } else {
    //                 return $this->randomTag($tags, $targes);
    //             }
    //         }
    //     }
    // }
    // public function temp()
    // {
    //     $tags = StatusAliasModel::where('alias', 'company/corporate_welfare')->column('value');
    //     $result = JobsModel::withTrashed()->select();
    //     for ($i = 0; $i < count($result); $i++) {
    //         $item = $result[$i];
    //         $random = $this->randomTag([], $tags);
    //         sort($random);
    //         $random = implode(',', $random);
    //         $item->jobs_welfare = $random;
    //         // $sql = JobsModel::where('id', $item->id)->fetchSql()->update(['jobs_welfare' => $item->jobs_welfare, 'update_time' => strtotime($item->update_time)]);
    //         $sql = "UPDATE `xy_jobs` SET `jobs_welfare` = '{$item->jobs_welfare}' WHERE ( `id` = {$item->id} )";
    //         echo $sql . ";<br />";
    //     }
    // }

}
